<?php
require_once dirname(dirname(__FILE__)) .'/cse-init.php';

// authentication is required!
Cinnamon::registry('session')->applyAuthenticationPolicy();

// load required classes
Cinnamon::loadClass('TabbedPane');
Cinnamon::loadClass('DataGrid');
Cinnamon::loadClass('Text');

// fetch required object from registry
$view = Cinnamon::registry('view');
$db = Cinnamon::registry('db');


// most recent requests
$mostRecent = $db->requests('request_id, request_url, request_title, request_datetime, ip_address, referrer_domain, visit_id')
				 ->order('request_datetime', 'DESC');

// most popular requests
$mostPopular = $db->requests('COUNT(request_id) AS visits, request_url, request_title, visit_id')
				  ->group('request_url, request_title')->order('visits', 'DESC');

//
// Pages
//
$pages = new TabbedPane('Pages');

//global $visit_id;

function pageLabelFunction($item) {
	static $visit_id;
	$item->request_title = ( empty($item->request_title) ) ? $item->request_url : $item->request_title;
	$item->referrer_domain = ( empty($item->referrer_domain) ) ? '' : ' / From: '.$item->referrer_domain;
	
	$onmouseover = '$(\'#'.$item->request_id.'\').attr(\'style\',\'font-size: 7pt; display:inline; color:#b8b8b8\')';
	$onmouseout = '$(\'#'.$item->request_id.'\').attr(\'style\',\'display:none\')';
	
	$followUp = ($item->visit_id == $visit_id) ? '<span style="color:#b8b8b8;">&#8594; <span>' : '';
	
	$visit_id = $item->visit_id;
	return $followUp.'<a href="'. $item->request_url .'" title="'. $item->request_title .'" onmouseover="'.$onmouseover.'" onmouseout="'.$onmouseout.'">'. $item->request_title .'</a>&nbsp; <span id="'.$item->request_id.'" class="hidden">IP: '.$item->ip_address.$item->referrer_domain.'</span>';
}

// Pages > Most recent
$dg = new DataGrid('Most recent');
$dg->pagination = true;
$dg->addColumn('Page', 'function', 'pageLabelFunction', 'format', 'nowrap');
$dg->addColumn('When', 'field', 'request_datetime', 'width', 100);

$dp = clone $mostRecent;
$dp->filter('request_type = ?', 'page');
$dg->setDataProvider($dp);

$pages->addChild($dg);

// Pages > Most popular
$dg = new DataGrid('Most popular');
$dg->pagination = true;
$dg->addColumn('Page', 'function', 'pageLabelFunction', 'format', 'nowrap');
$dg->addColumn('Visits', 'field', 'visits', 'width', 50);

$dp = clone $mostPopular;
$dp->filter('request_type = ?', 'page');
$dg->setDataProvider($dp);

$pages->addChild($dg);

//
// Downloads
//
$downloads = clone $pages;
$downloads->title = 'Downloads';

// Downloads > Most recent
$dg = $downloads->getChildAt(0);

$dp = clone $mostRecent;
$dp->filter('request_type = ?', 'download');
$dg->setDataProvider($dp);

// Downloads > Most popular
$dg = $downloads->getChildAt(1);

$dp = clone $mostPopular;
$dp->filter('request_type = ?', 'download');
$dg->setDataProvider($dp);

// render output
$view->addChild($pages);
$view->addChild($downloads);
$view->render();
?>